package cz.boxdesign.library.configuration;

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;

public class DatabaseOperation {

	private Connection connection;

	private String driverName;
	private String url;
	private String user;
	private String password;

	public DatabaseOperation() {

	}

	public DatabaseOperation(Connection connection, String driverName, String url, String user, String password) {
		super();
		this.connection = connection;
		this.driverName = driverName;
		this.url = url;
		this.user = user;
		this.password = password;
	}

	public void reconect() {
		try {
			this.connection.close();
			Class.forName(driverName);
			this.connection = DriverManager.getConnection(url, user, password);
		} catch (SQLException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}

	public Statement getSatement() {
		try {
			return connection.createStatement();
		} catch (SQLException e) {
			return null;
		}
	}

	public PreparedStatement getPreparedStatement(String sql) {
		try {
			return connection.prepareStatement(sql);
		} catch (SQLException e) {
			return null;
		}
	}

	public CallableStatement getCallableStatement(String sql) {
		try {
			return connection.prepareCall(sql);
		} catch (SQLException e) {
			return null;
		}
	}

	/**
	 * Close.
	 **/
	public boolean close() {
		boolean ret = true;
		try {
			connection.close();
		} catch (SQLException ex) {
			ret = false;
		}
		return ret;
	}

	/**
	 * Begin a transaction.
	 **/
	public boolean beginTransaction() {
		boolean ret = true;
		try {
			connection.setAutoCommit(false);
			connection.setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE);
		} catch (SQLException ex) {
			ret = false;
		}
		return ret;
	}

	/**
	 * End a transaction.
	 **/
	public boolean endTransaction() {
		boolean ret = true;
		try {
			connection.commit();
			connection.setAutoCommit(true);
		} catch (SQLException ex) {
			ret = false;
		}
		return ret;
	}

	/**
	 * If a transaction is failed call it.
	 **/
	public boolean rollback() {
		boolean ret = true;
		try {
			connection.rollback();
			connection.setAutoCommit(true);
		} catch (SQLException ex) {
			ret = false;
		}
		return ret;
	}

	public Connection getConnection() {
		return connection;
	}

	/**
	 * @param connection
	 *            the connection to set
	 */
	public void setConnection(Connection connection) {
		this.connection = connection;
	}

}
